﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using DBBase;

using System.Threading;

using System.IO;

using System.Web;
using System.Runtime.InteropServices;
using System.IO.Ports;

namespace Business
{
    public partial class mimachongzhi : Form
    {
        public MainForm m_mainform;

        public static string uid;
        public static string name;
        public static string bianhao;
        public static string yuanmima;

        // /声明INI文件的写操作函数 WritePrivateProfileString()
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        //声明INI文件的读操作函数 GetPrivateProfileString()
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        private string sPath = null;
        public static string sip;
        public static string zhanghao;

        public mimachongzhi(string suid,string sname,string sbianhao,string syuanmima,string szhanghao)
        {
            InitializeComponent();
            uid = suid;
            name = sname;
            bianhao = sbianhao;
            yuanmima = syuanmima;
            zhanghao = szhanghao;

            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\本机信息.ini";
            string path1 = string.Format(@"{0}", path);
            Ini(path1);


            sip = ReadValue("设置", "IP");

        }
        //ini文件
        public void Ini(string path)
        {
            this.sPath = path;
        }
        public void Writue(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径
            WritePrivateProfileString(section, key, value, sPath);
        }
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

            // section=配置节，key=键名，temp=上面，path=路径
            GetPrivateProfileString(section, key, "", temp, 255, sPath);
            return temp.ToString();
        }
        //ini文件
        private string Encryption(string express)//加密
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = "gzwk2006";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] plaindate = Encoding.Default.GetBytes(express);
                byte[] encryptdate = rsa.Encrypt(plaindate, false);

                return Convert.ToBase64String(encryptdate);
            }
        }
        //
        private string Decrypt(string cip)//解密
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = "gzwk2006";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] encryptdate = Convert.FromBase64String(cip);
                byte[] decryptdate = rsa.Decrypt(encryptdate, false);
                return Encoding.Default.GetString(decryptdate);
            }
        }
        public void updatemima()
        {
            string smima="";
            smima=Encryption(string.Format("{0}{1}{2}{3}",uid,name,bianhao,text_mima.Text));
            Query objquery = new Query();
            string ssql = "";
            ssql = string.Format(@"update  USERE set PASSWORD='{0}' where NAME='{1}'", smima, name);
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("密码修改失败");
                //baocundlrj(zhanghao, "修改用户密码", "失败");
            }
            else
            {
                MessageBox.Show("密码修改成功");
                //baocundlrj(zhanghao, "修改用户密码", "成功");
            }
            string sneirong = "";
            sneirong = string.Format(@"用户于{0}进行了用户密码重置操作，操作关键信息为{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "update USERE表");
          //  baocunhxrj("用户密码重置", zhanghao, sneirong);

            //保存操作日记
            m_mainform.savecaozuoriji(ssql, "更新", "系统管理", "用户密码重置");

        }
       
        public void baocundlrj(string syonghuming, string dllx, string sfcg)// 用户明 登录类型 是否成功
        {
            Query objquery = new Query();
            string ssql = "";

            ssql = string.Format(@"insert into dengluriji (username,dengluIP,dlqk,dlsj,dlsfcg) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}',
                                    '{4}')",
                                    syonghuming,
                                    sip,
                                    dllx,
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                    sfcg);
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }

        public void baocunshrj(string saqcl, string syonghuming, string srjnr)// 安全策略 用户名 日记内容
        {
            Query objquery = new Query();
            string ssql = "";

            ssql = string.Format(@"insert into shenjiriji (shrj_aqcl,shrj_yhdh,shrj_rjnr,shrj_sjsj) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}')",
                                    saqcl,
                                    syonghuming,
                                    srjnr,
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }
       
        public void baocunhxrj(string saqcl, string syonghuming, string srjnr)// 核心功能日记 用户名 日记内容
        {
            Query objquery = new Query();
            string ssql = "";
            ssql = string.Format(@"insert into hexinriji (shrj_aqcl,shrj_yhdh,shrj_yhip,shrj_rjnr,shrj_sjsj) values 
                                    ('{0}',
                                    '{1}',
                                    '{2}',
                                    '{3}',
                                    '{4}')",
                                    saqcl,
                                    syonghuming,
                                    sip,
                                    Encryption(srjnr),
                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (!objquery.UpdateTable(ssql))
            {
                MessageBox.Show("添加失败");
            }
        }
       

        private void but_query_Click(object sender, EventArgs e)
        {
            string s =
@"  
(?=.*[0-9])                         #必须包含数字  
(?=.*[a-zA-Z])                      #必须包含小写或大写字母  
(?=([\x21-\x7e]+)[^a-zA-Z0-9])      #必须包含特殊符号  
.{8,20}                             #至少8个字符，最多20个字符  
";
            //if (text_mima.Text.Length < 8 || text_mima.Text.Length>20)
            //{
            //    MessageBox.Show("密码长度必须为8~20位");
            //    return;
            //}
            //if (!(System.Text.RegularExpressions.Regex.IsMatch(text_mima.Text, "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]+$")))
            //{

            //    MessageBox.Show("密码必须包含数字和字母");
            //    return;
            //}
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(s, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);
            if (!reg.IsMatch(text_mima.Text.Trim()))
            {
                MessageBox.Show("密码必须至少8个字符，最多20个字符，\r\n并且至少有1个字母、\r\n至少有1个数字、\r\n至少有1个特殊字符!");
                return;
            }

          
           

            try
            {
                string test = Decrypt(yuanmima);
            }
            catch
            {
                MessageBox.Show("数据异常 原密码校验不通过");
                //baocunaqrj(zhanghao, "数据异常", "原密码校验不通过");
                m_mainform.baocunaqrj("密码修改", "更改", "系统管理", "否", "否", "失败", string.Format("用户{0}原密码校验不通过", name));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                return;
            }

            if (text_ymima.Text == "admin_888888")
            {
                string stest = "";
                try
                {
                    stest = Decrypt(yuanmima);
                }
                catch
                {
                  //  baocunaqrj(zhanghao, "数据异常", "原密码校验不通过");
                    m_mainform.baocunaqrj("密码修改", "更改", "系统管理", "否", "否", "失败", string.Format("用户{0}原密码校验不通过", name));//事件、类型（增、删、该、查）、模块、是否核心功能、是否非常规业务、结果和描述

                }
                if (Decrypt(yuanmima).Contains("admin_888888"))
                {
                    if (text_mima.Text == text_cfmima.Text)
                    {
                        updatemima();
                    }
                    else
                    {
                        MessageBox.Show("密码不一致");
                    }
                }
                else
                {
                    MessageBox.Show("原密码错误");
                }
            }
            else
            {
                Query mquery = new Query();
                string sql;
                sql = string.Format(@"Select * from USERE   Where NAME='{0}'", name);
                DataTable dt = mquery.GetTable(sql);
                if (dt.Rows.Count > 0)
                {
                    string syuanmima = "";
                    syuanmima = dt.Rows[0]["PASSWORD"].ToString().Trim();
                    uid = dt.Rows[0]["UID"].ToString().Trim();
                    name = dt.Rows[0]["NAME"].ToString().Trim();
                    bianhao = dt.Rows[0]["GZRYBH"].ToString().Trim();

                    string smima = "";
                    smima = (string.Format("{0}{1}{2}{3}", uid, name, bianhao, text_ymima.Text));
                    if (Decrypt(syuanmima) == smima)
                    {
                        updatemima();
                    }
                    else
                    {
                        MessageBox.Show("原密码错误");
                    }
                }
                else
                {
                    MessageBox.Show("用户不存在");
                }

            }
            this.Close();
        }

        private void but_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
